package com.dlc.shop.jky.platform.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linchuang.seneca.jky.bizdata.vend.vendcreate.core.VendCreateRequestBizData;
import com.linchuang.seneca.jky.bizdata.vend.vendcreate.core.VendCreateResponseBizData;
import com.linchuang.seneca.jky.bizdata.vend.vendget.core.VendGetResponseBizData;
import com.linchuang.seneca.jky.exception.JkyException;
import com.dlc.shop.bean.bo.PayInfoResultBO;
import com.dlc.shop.bean.enums.OrderStatus;
import com.dlc.shop.bean.enums.PayStatus;
import com.dlc.shop.bean.model.OfflineHandleEvent;
import com.dlc.shop.bean.model.Order;
import com.dlc.shop.bean.model.PayInfo;
import com.dlc.shop.bean.param.OfflineHandleEventAuditParam;
import com.dlc.shop.common.enums.PayType;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.config.ShopConfig;
import com.dlc.shop.jky.common.foreign.service.ForeignShopService;
import com.dlc.shop.jky.common.service.ErpVendCreateV2Service;
import com.dlc.shop.jky.common.service.JkyService;
import com.dlc.shop.manager.impl.PayManager;
import com.dlc.shop.service.OrderService;
import com.dlc.shop.service.PayInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@RestController
@RequestMapping("/jkyShop")
@Tag(name = "吉客云使用")
@AllArgsConstructor
public class jkyMallController {

    public final ShopConfig shopConfig;
    public final JkyService jkyService;
    public final ErpVendCreateV2Service erpVendCreateV2Service;
    public final ForeignShopService foreignShopService;
    public final OrderService orderService;
    public final PayInfoService payInfoService;
    public final PayManager payManager;

    @GetMapping("/list")
    @Operation(summary = "查询供应商信息" , description = "查询供应商信息")
    public ServerResponseEntity<VendGetResponseBizData> dvyList() {
        // 默认将默认地址放在首位
      // VendGetResponseBizData vendGetResponseBizData = null;
      // try {
      //     vendGetResponseBizData = jkyService.getVendGetResponseBizData();
      // } catch (JkyException e) {
      //     e.printStackTrace();
      //     return ServerResponseEntity.fail(e.getCode(),e.getDesc());
      // }
        List<Order> orders = orderService.listUnRefundOrderAndOrderItems(OrderStatus.UNPAY.value(), DateUtil.offsetMinute(new Date(), -30));

        List<Order> cancelOrderList = this.checkOrders(orders);
        orderService.cancelOrders(cancelOrderList);
        return ServerResponseEntity.success();
    }
    /**
     * 查询订单，去除已支付的订单
     *
     * @param orders
     */
    private List<Order> checkOrders(List<Order> orders) {
        // 收集未支付的订单
        List<Order> orderList = new ArrayList<>();
        for (Order order : orders) {
            // 获取支付过的信息
            List<PayInfo> payInfoList = payInfoService.list(new LambdaQueryWrapper<PayInfo>().like(PayInfo::getOrderNumbers, order.getOrderNumber()));
            if (CollectionUtil.isEmpty(payInfoList)) {
                orderList.add(order);
                continue;
            }
            boolean unPay = true;
            for (PayInfo payInfo : payInfoList) {
                String bizPayNo = null;
                if (Objects.nonNull(payInfo.getPayNo())) {
                    bizPayNo = payInfo.getBizPayNo();
                }
                PayInfoResultBO payInfoResultBO = payManager.getPayHuiFuInfo(PayType.instance(payInfo.getPayType()),
                        payInfo.getPayNo(), payInfo.getPaySysType(), bizPayNo, payInfo.getReqDate());
                // 如果之前是已经支付成功过的，直接更新订单
                if (payInfoResultBO.getIsPaySuccess()) {
                    // 根据内部订单号更新order settlement
                    if (Objects.equals(payInfo.getPayStatus(), PayStatus.UNPAY.value())) {
                        payInfoService.noticeOrder(payInfoResultBO, payInfo, payInfoResultBO.getPaySysType());
                    }
                    unPay = false;
                    break;
                }
            }
            // 没有支付过就直接取消订单
            if (unPay) {
                orderList.add(order);
            }
        }
        return orderList;
    }

    @GetMapping("/add")
    @Operation(summary = "添加更新供应商" , description = "添加更新供应商")
    public ServerResponseEntity<List<VendCreateResponseBizData>> erpVendCreateV2() {
        // 默认将默认地址放在首位
        List<VendCreateResponseBizData> vendCreateResponseBizData = null;
        try {
            VendCreateRequestBizData vendCreateRequestBizData = new VendCreateRequestBizData();
            vendCreateResponseBizData = erpVendCreateV2Service.erpVendCreateV2(vendCreateRequestBizData,1l);
        } catch (JkyException e) {
            e.printStackTrace();
            return ServerResponseEntity.fail(e.getCode(),e.getDesc());
        }
        return ServerResponseEntity.success(vendCreateResponseBizData);
    }

    @PostMapping("/goodsSourceCreate")

    @Operation(summary = "erp.goodssource.create(根据条码和供应商编号创建供应商报价)" , description = "erp.goodssource.create(根据条码和供应商编号创建供应商报价)")
    public ServerResponseEntity<List<VendCreateResponseBizData>> goodsSourceCreate(@RequestBody List<Long> prodIds) {
        // 默认将默认地址放在首位
        try {
            erpVendCreateV2Service.GoodsSourceCreate(1,10);
        } catch (JkyException e) {
            e.printStackTrace();
            return ServerResponseEntity.fail(e.getCode(),e.getDesc());
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/send")
    @Operation(summary = "send" , description = "send")
    public ServerResponseEntity send() {
        // 默认将默认地址放在首位
        try {
            foreignShopService.shopCreateInfo(5L);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponseEntity.fail(e.getMessage(),e.toString());
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/offline")
    @Operation(summary = "offline 下线店铺" , description = "offline")
    public ServerResponseEntity offline(OfflineHandleEvent offlineHandleEvent ) {
        // 默认将默认地址放在首位
       String i = "";
        try {

             i=foreignShopService.offline( offlineHandleEvent);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponseEntity.fail(e.getMessage(),e.toString());
        }
        return ServerResponseEntity.success(i);
    }

    @GetMapping("/auditShop")
    @Operation(summary = "auditShop 审核上线店铺" , description = "auditShop")
    public ServerResponseEntity auditShop(OfflineHandleEventAuditParam offlineHandleEventAuditParam ) {
        // 默认将默认地址放在首位
       String i = "";
        try {
             i=foreignShopService.auditShop( offlineHandleEventAuditParam);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponseEntity.fail(e.getMessage(),e.toString());
        }
        return ServerResponseEntity.success(i);
    }
    @GetMapping("/auditApply")    @Operation(summary = "违规店铺重新提交审核", description = "违规店铺重新提交审核")

    public ServerResponseEntity auditApply(OfflineHandleEventAuditParam offlineHandleEventAuditParam ) {
        // 默认将默认地址放在首位
       String i = "";
        try {
             i=foreignShopService.auditApply( offlineHandleEventAuditParam);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponseEntity.fail(e.getMessage(),e.toString());
        }
        return ServerResponseEntity.success(i);
    }

}
